<template>
    <view class="container">
        <view class="lines u-flex u-row-between u-col-center" @click="changeAvatar">
            <view class="head">头像</view>
            <view class="u-flex u-col-center" @click.stop>
                <u-avatar :src="url" size="120" mode="circle"  @click="preview(url)"></u-avatar>
                <view class="icon icon-right u-m-l-20" @click="changeAvatar"></view>
            </view>
        </view>
        <view class="lines u-flex u-row-between u-col-center" @click="$u.$MRouter.setNickName.to()">
            <view class="head">昵称</view>
            <view class="u-flex u-col-center">
                <text class="text">{{ name || '设置个性昵称' }}</text>
                <view class="icon icon-right u-m-l-20"></view>
            </view>
        </view>
        <view class="lines u-flex u-row-between u-col-center" @click="showSex = true">
            <view class="head">性别</view>
            <view class="u-flex u-col-center">
                <text class="text">{{ sex === 0 ? '男' : '女' }}</text>
                <view class="icon icon-right u-m-l-20"></view>
            </view>
        </view>
        <!--认证完 才显示 该模块  -->
        <view v-if="status == 4">
            <view class="title">
                信息档案
                <text class="sub">(完成度{{percent}}%)</text>
            </view>
            <view class="lines u-flex u-row-between u-col-center" @click="router('base')">
                <view class="head">基本信息</view>
                <view class="u-flex u-col-center">
                    <text class="text" :class="{done:done[0]}">{{done[0] ? '已完成' : '待完善'}}</text>
                    <view class="icon icon-right u-m-l-20"></view>
                </view>
            </view>
            <view class="lines u-flex u-row-between u-col-center" @click="router('bank')">
                <view class="head">银行账户信息</view>
                <view class="u-flex u-col-center">
                    <text class="text" :class="{done:done[1]}">{{done[1] ? '已完成' : '待完善'}}</text>
                    <view class="icon icon-right u-m-l-20"></view>
                </view>
            </view>
            <view class="lines u-flex u-row-between u-col-center" @click="router('signboard')">
                <view class="head">{{`门头照/营业执照`}}</view>
                <view class="u-flex u-col-center">
                    <text class="text" :class="{done:done[2]}">{{done[2] ? '已完成' : '待上传'}}</text>
                    <view class="icon icon-right u-m-l-20"></view>
                </view>
            </view>
            <view class="lines u-flex u-row-between u-col-center" @click="router('invoice')">
                <view class="head">开票信息</view>
                <view class="u-flex u-col-center">
                    <text class="text" :class="{done:done[3]}">{{done[3] ? '已完成' : '待完善'}}</text>
                    <view class="icon icon-right u-m-l-20"></view>
                </view>
            </view>
            <view class="lines u-flex u-row-between u-col-center" @click="router('contact')">
                <view class="head">联系人信息</view>
                <view class="u-flex u-col-center">
                    <text class="text" :class="{done:done[4]}">{{done[4] ? '已完成' : '待完善'}}</text>
                    <view class="icon icon-right u-m-l-20"></view>
                </view>
            </view>
            <view class="lines u-flex u-row-between u-col-center" @click="router('other')">
                <view class="head">其他</view>
                <view class="u-flex u-col-center">
                    <text class="text" :class="{done:done[5]}">{{done[5] ? '已完成' : '待添加'}}</text>
                    <view class="icon icon-right u-m-l-20"></view>
                </view>
            </view>
            <view class="tips u-flex u-row-center u-col-center">
                <text class="icon">&#xe631;</text>
                <text>完成个人信息档案可享受平台授信服务</text>
            </view>
        </view>
        <u-action-sheet :list="sexlist" @click="changeSex" v-model="showSex" safe-area-inset-bottom></u-action-sheet>
        <u-modal v-model="showModal" title="没有权限" :content="content" show-cancel-button confirm-text="去设置" @confirm="confirm"></u-modal>
    </view>
</template>

<script lang="ts" setup>
import global from '@/config'
import { useGlobalStore, useUserStore } from '@/store'
import { computed, onUnmounted, ref } from 'vue';
import { onReady } from '@dcloudio/uni-app';

const url = ref('')
const name = ref('')
const sex = ref(0)
const showSex = ref(false)
const content = ref('')
const showModal = ref(false)
const sexlist = ref([{ text: '男' }, { text: '女' }])
const actionList = ref([{ text: '手机相册' }, { text: '拍照上传' }])
const isShowImg = ref(false)
const percent = ref(0)
const done = ref<Array<any>>([])

const globalStore = useGlobalStore()
const userStore = useUserStore()

const status = computed(()=>{
    return userStore.config.authStatus
})
const $u = computed(()=>{
    return uni.$u
})
const type = computed(()=>{
    return userStore.userInfo.type
})

// 修改头像
function changeAvatar() {
    // #ifdef H5
    uni.$u.toast('H5 不支持')
    // #endif

    // #ifdef APP-PLUS
    uni.chooseImage({
        count:1,
        crop:{
            quality:100,
            width:300,
            height:300
        },
        success: (res) => {
            uni.uploadFile({
                url:`${global.BASE_URL_API}/file/file-view/uploadHeadPicUrl`,
                filePath:res.tempFilePaths[0],
                name: 'file',
                header: {
                    'content-type': 'multipart/form-data'
                },
                success:(ress)=> {
                    const avatar = JSON.parse(ress.data).data
                    url.value = avatar
                    updateProfile()
                },
                fail:(error)=>{
                    uni.$u.toast(error.errMsg)
                }
            })
        },
        fail: async (err) => {
            if (err.errCode == 12 && uni.$u.os() != 'ios') {
                // let STORAGE = await globalStore.permission.requestAndroidPermission('android.permission.READ_EXTERNAL_STORAGE')
                // let CAMERA = await permission.requestAndroidPermission('android.permission.CAMERA')
                // if (STORAGE == -1 || CAMERA == -1 ) {
                //     content.value = `${STORAGE === 1 ? '':'存储'}${CAMERA === 1? '':'相机'}权限未授予,请先授予权限`
                //     showModal.value = true
                //     return
                // }
            }
        }
    })
    // #endif
}

function router(name: string){
    uni.navigateTo({
        url: `./information/${name}`
    })
}

function confirm(){
    // globalStore.permission.gotoAppPermissionSetting()
}

function updateProfile() {
    let data = {
        headPicUrl: url.value,
        nickname: name.value,
        sex: sex.value
    }
    // vuex中 并不知道 修改的是什么 因此 需要在这里 保存 store
    userStore.updateProfile({ data }).then(() => {
        uni.$u.toast('修改成功!')
    })
}

// 修改性别
function changeSex(index: number) {
    sex.value = index
    updateProfile()
}

function preview(url: string) {
    uni.previewImage({
        urls: [url]
    })
}

function init(){
    percent.value = 0
    let merchantId = userStore.userInfo.merchantId
    if (!merchantId) return uni.$u.toast('非法商户id，请检查登录状态!')

    uni.$u.$api.MerchantApi.appMerchantDetail({id:merchantId}).then((res: any)=>{
        let account = res.account
        url.value = account.headPicUrl
        name.value = account.nickname
        sex.value = account.sex || 0

        userStore.updateDetai(res)
        // 检查 认证非必填项 是否有数据
        // 1.渠道 2.地址  3.详细地址
        let merchant = res.merchant
        if (merchant.provinceCode && merchant.detailAddress && res.channels.length > 0) {
            done.value[0] = true
            percent.value += 20
        }
        let bank = res.bank || {}
        // 1.开户许可证  2.开户行 3.银行账号  4.账号 需要根据 用户类型判断
        if([1,2].indexOf(type.value) > -1){
            if (bank.bankAccountNo && bank.bankName && bank.pictures.length > 0){
                done.value[1] = true
                percent.value += 20
            }
        }else{
            if (bank.bankAccountName && bank.bankAccountNo && bank.bankName && bank.pictures.length > 0){
                done.value[1] = true
                percent.value += 20
            }
        }

        //  1.营业执照  2.门头照  需要根据 用户类型判断
        if([0,1].indexOf(type.value) > -1){
            if (merchant.shopPicId && merchant.socialCodePic) {
                done.value[2] = true
                percent.value += 20
            }
        }else{
            if (merchant.shopPicId) {
                done.value[2] = true
                percent.value += 20
            }
        }
        // 开票信息
        if (res.taxList.length > 0 ) {
            done.value[3] = true
            percent.value += 20
        }
        if (res.contactsList.length > 1) {
            done.value[4] = true
            percent.value += 20
        }
        if (uni.getStorageSync('cf-merchant-marks').length > 0){
            done.value[5] = true
        }
    })
}

onReady(()=>{
    uni.$on('setName', name => {
        name.value = name
        updateProfile()
    })
    init()
})

onUnmounted(()=>{
    uni.$off('setName')
})
</script>

<style scoped lang="scss">
.container {
    height: calc(100vh - 44px - var(--status-bar-height));
    padding: 20rpx 0;
    .title{
        padding: 30rpx;
        font-size: 34rpx;
        margin-top: 30rpx;
        font-weight: bold;
        .sub{
            color: #999999;
            font-size: 26rpx;
            margin-left: 20rpx;
        }
    }
    .lines {
        height: 140rpx;
        background-color: $uni-bg-color;
        padding: 10rpx 30rpx;
        margin-bottom: 4rpx;
        font-size: 30rpx;
        border-radius: 10rpx;

        .head {
            font-weight: 600;
            line-height: 60rpx;
        }

        .text {
            color: #a6a6a6;
            line-height: 60rpx;
        }
        .done{
            color: #55aa7f;
        }
    }
    .tips{
        font-size: 26rpx;
        color: #999999;
        padding: 40rpx 0;
        & > text{
            margin-right: 20rpx;
        }
    }
}
</style>
